import { Injectable } from "@angular/core";
import {
  HttpErrorResponse,
  HttpEvent,
  HttpHandler, HttpHeaders,
  HttpInterceptor,
  HttpRequest,
  HttpResponse
} from "@angular/common/http";
import { Observable, of } from "rxjs";
import { CommService } from "./comm-service";
import { catchError, map, mergeMap, tap } from "rxjs/internal/operators";
import { Router } from "@angular/router";


@Injectable()

export class MyhttpInterceptorService implements HttpInterceptor {
  constructor(private commservice: CommService,
    private router: Router) {

  }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // 拦截请求体，加上5个公共参数
    const basereqobj = req.body;
    const reqobj = (basereqobj === null) ? {} : basereqobj;
    const pubbodyparam = this.commservice.getpubbodyParams();
    for (let key in pubbodyparam) {
      reqobj[key] = pubbodyparam[key];
    }
    // 拦截请求头，处理加密和 token
    let header = new HttpHeaders().set("Content-Type", "application/json;charset=UTF-8");
    const baseurl = req.url;
    const notReqsignkey_sigkeyobjlist = ["manager/getConnToken", "manager/captcha", "hubei/oauth/getToken"]; // 不需要，追加  signkey和 对入参做 signkey加密的接口
    if (notReqsignkey_sigkeyobjlist.indexOf(baseurl) == -1) {
      const pubheaderparams1 = this.commservice.getpubheaderParams1(reqobj);
      header = header.set("xc_client_sessionid", pubheaderparams1.signkey);
      header = header.set("Content-Signature", pubheaderparams1.signreqobj);
      const notReqaccesstoken_yzlist = ["manager/getAccessToken", "manager/secret/getAccessToken", "manager/user/getMobile", "manager/user/sendLoginMsg"]; // 不需要用户验证信息的接口
      if (notReqaccesstoken_yzlist.indexOf(baseurl) == -1) {
        const pubheaderparams2 = this.commservice.getpubheaderParams2();
        header = header.set("xc_sso_sessionid", pubheaderparams2.access_token);
        header = header.set("Authorization", pubheaderparams2.Authorization);
      }
    }
    //const url = "http://173.0.0.11:7979/" + baseurl;  //浙江省考院
    //const url = "http://101.71.249.36:7979/" + baseurl;  //浙江省考院外网
    // const url = "http://172.16.15.228:7979/" + baseurl;  //山西省
   //const url = "http://47.111.5.196:7979/" + baseurl;  //阿里云
    const url = "https://www.hbjyks.cn:19000/" + baseurl;
    //const url = `${location.protocol}//${location.hostname}:7979/${baseurl}`;  //阿里云相对
    //const url = "http://192.168.156.167:7979/" + baseurl;  //郑州167
    //const url = "http://127.0.0.1:7979/" + baseurl;
    //const url = "http://192.168.157.37:7979/" + baseurl;  //37
    //const url = "https://www.sneac.edu.cn/plateformApi/" + baseurl;  //陕西
    //const url = "http://101.71.241.116:1179/" + baseurl;  //杭州考试院

    // const url = "http://119.96.170.205:7979/" + baseurl;  //湖北平台-----未集成演示用的试卷跟踪
   
    const authReq = req.clone({
      url, headers: header, body: reqobj
    });
    // 响应拦截处理
    return next.handle(authReq).pipe(
      map((resp: any) => {
        if (resp.type) {
          const httpstatus = resp.status;
          if (httpstatus === 200) {
            // http 请求状态码是 200
            const respbody = resp.body;
            const ywcode = respbody.code; // 业务接口code 【8001(signkey 失效)】,【 200】【其他的失败直接抛出 message】
            //const ywmsg = respbody.message; // 业务接口提示信息
            // const ywresult = respbody.result;// 业务接口返回的数据
            if (ywcode === 8001) {
              // 【signkey 失效】， 重新获取signkey 并且 重新请求
              // 改写返回中的code值
              respbody.code = 202;
            }
            // 【 200】【其他的失败直接抛出 message】
            resp.body = respbody;  // 可以处理返回数据  resp.body  ==== subscribe(resp)
          }
        }
        return resp;
      }),
      catchError((err: HttpErrorResponse) => {

        // http 请求状态码不是 200
        return this.handleData(err);
      })
    )
  }

  /**
   * 服务器错误拦截
   * @param {HttpErrorResponse | HttpResponse<any>} event
   * @returns {Observable<any>}
   */
  handleData(event: HttpErrorResponse | HttpResponse<any>): Observable<any> {
    const status = event.status;
    const statusText = event.statusText;
    const errorRequstUrl = event.url;
    if (status == 401) {
      this.commservice.warn(errorRequstUrl, status + ":" + statusText, "");
      this.router.navigate(["login"]);
    } else if (status == 500) {
      this.commservice.warn(errorRequstUrl, status + ":" + statusText, "");
    }
    return of([]);
  }


}
